<template>
  <a-modal v-if="modelValue" v-model:visible="modelValue" width="80%" @ok="handleOk" :title="t('org.role.addRoleBtn')">
    <qc-page-table
      ref="rolePageTableRef"
      :columns="columns"
      :loadData="loadData"
      :rowKey="(record) => record[primaryKey]"
      :cardBordered="true"
      :bordered="true"
    >
      <template #toolbarTitle>
        {{ t('org.role.roleTableTitle') }}
      </template>
      <template #toolbarButton>
        <a-input-search
          :placeholder="t('org.role.roleTableSerachPlh')"
          v-model:value="queryParam.roleName"
          @search="onTableSearch"
        ></a-input-search>
      </template>
      <template #customRoleType="{ text, record }">
        <a-tag :color="record.roleType === 'MANAGER_ROLE' ? 'volcano' : 'purple'">
          {{ text }}
        </a-tag>
      </template>
      <template #customIsValid="{ text }">
        <a-tag v-if="text === true" color="#87d068">
          {{ t('org.role.effective') }}
        </a-tag>
        <a-tag v-else color="#f50">
          {{ t('org.role.invalid') }}
        </a-tag>
      </template>
    </qc-page-table>
  </a-modal>
</template>
<script lang='ts'>
import { defineComponent, nextTick, reactive, ref, toRefs, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import roleApi from '/@/api/org/role'
import { roleTableColumns } from '/@/views/org/role/interface'
import { useModelPageTable } from '/@/kit/model-kit'
import { isBlankForArray } from '/@/kit/blank-kit'
import { message } from 'ant-design-vue'
export default defineComponent({
  name: 'RoleSelectModal',
  props: {
    //是否显示弹层
    value: {
      type: Boolean,
      default: false,
    },
    userId: String,
  },
  emits: ['update:value', 'selectRoleOk'],
  setup(props, { emit }) {
    const { t } = useI18n()
    const rolePageTableRef = ref(null)
    const queryParam = { roleName: null, excludeUserId: props.userId }
    //v-model双向绑定
    const modelValue = ref(props.value)
    watch(
      () => props.value,
      (val) => (modelValue.value = val)
    )
    watch(modelValue, (val) => {
      if (val) nextTick(() => searchTable())
      emit('update:value', val)
    })

    //table 使用
    const { primaryKey, loadData, searchTable, reloadTable, getSelectRows } = useModelPageTable(
      rolePageTableRef,
      roleApi,
      queryParam
    )

    const roleState = reactive({
      queryParam,
      //表格字段
      columns: roleTableColumns,
      primaryKey,
      loadData,
      onTableSearch: () => reloadTable(),
      handleOk: () => {
        const roleList = getSelectRows()
        if (isBlankForArray(roleList)) {
          message.warning(t('org.user.notSelectedUser'))
          return
        }
        emit('selectRoleOk', roleList)
      },
    })

    return {
      t,
      rolePageTableRef,
      modelValue,
      ...toRefs(roleState),
    }
  },
})
</script>